#include "../include/dbconn_pool.h"

// 数据库连接

int db_conn_pool_init(dbConnPool_t *dbconnPool, int workernum) {
    dbconnPool->connNum = workernum;
    dbconnPool->statusArr = (int*)calloc(workernum, sizeof(int));
    ERROR_CHECK(dbconnPool->statusArr, NULL, "calloc when create connectpool");
    dbconnPool->dbConnArr = (MYSQL**)calloc(workernum, sizeof(MYSQL*));
    ERROR_CHECK(dbconnPool->dbConnArr, NULL, "calloc when create connectpool");
    for (int i = 0; i < workernum; i++) {
        dbconnPool->dbConnArr[i] = mysql_init(NULL);
        MYSQL* res = mysql_real_connect(dbconnPool->dbConnArr[i], "localhost",
                                        "root", "123456", "cloud_disk", 0, NULL, 0);
        MYSQL_ERROR_CHECK(res, NULL, "mysql real connect", dbconnPool->dbConnArr[i]);
        dbconnPool->statusArr[i] = 1; // 成功建立连接
    }
    return 0;
}

int get_dbconn(dbConnPool_t *dbconnPool, MYSQL **mysql) {
    for (int i = 0; i < dbconnPool->connNum; i++) {
        if (dbconnPool->statusArr[i] == 1) {
            *mysql = dbconnPool->dbConnArr[i];
            dbconnPool->statusArr[i] = 0;
            return 0;
        }
    }
    return -1;
}
